package com.atguigu.tingshu.user.strategy.impl;

import java.util.Date;

import cn.hutool.Hutool;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Author  王东剑
 * Created on 24/6/2024 下午8:00
 * Package_name com.atguigu.tingshu.user.strategy.impl
 * Description
 */
@Slf4j
@Service
public class UserVipServiceStrategyImpl implements UpdateUserPaidRecordStrategy {
	@Autowired
	private UserVipServiceMapper userVipServiceMapper;
	@Autowired
	private VipServiceConfigService vipServiceConfigService;
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
		String orderNo = userPaidRecordVo.getOrderNo();
		List<Long> itemIdList = userPaidRecordVo.getItemIdList();
		Long userId = userPaidRecordVo.getUserId();
		Long itemId = itemIdList.get(0);
		// 	防止重复消费
		UserVipService isExists = userVipServiceMapper.selectOne(new LambdaQueryWrapper<UserVipService>().eq(UserVipService::getOrderNo, orderNo));
		if (Objects.nonNull(isExists)) return;
		// 	根据 VIP配置Id 获取对应的信息
		VipServiceConfig vipServiceConfig = vipServiceConfigService.getVipServiceConfig(itemId);
		UserInfo userInfo = userInfoService.getById(userId);
		Date startTime = new Date();
		if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(startTime)) {
			startTime = userInfo.getVipExpireTime();
		}
		DateTime vipExpireTime = DateUtil.offset(startTime, DateField.MONTH, vipServiceConfig.getServiceMonth());
		// 构造VIP信息并保存
		UserVipService userVipService = new UserVipService();
		userVipService.setOrderNo(orderNo);
		userVipService.setUserId(userId);
		userVipService.setStartTime(startTime);
		userVipService.setExpireTime(vipExpireTime);
		userVipServiceMapper.insert(userVipService);

		// 更新用户信息
		userInfo.setIsVip(1);
		userInfo.setVipExpireTime(vipExpireTime);
		userInfoService.updateById(userInfo);
	}

	@Override
	public String getItemType() {
		return SystemConstant.ORDER_ITEM_TYPE_VIP;
	}
}
